use crate::{
    PHYSIZE, SCALE_FACTOR, utils::{cache_util, date_util, window_util}
};
use base64::{engine::general_purpose, Engine};
use image::ImageFormat;
use image::{DynamicImage, ImageBuffer};
use rdev::{Event, Key};
use std::{
    io::Cursor,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, Mutex,
    },
    thread::sleep,
    time::{Duration, Instant},
};

use serde::Serialize;
#[cfg(target_os = "macos")]
use tauri::TitleBarStyle;
use tauri::{Emitter, Manager, Runtime};
use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_plugin_global_shortcut::{GlobalShortcutExt, ShortcutState};

pub fn create_host_key<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> {
    //let app_handle = app.clone();
    // tauri::async_runtime::spawn(async move {
    //     open_record(app_handle, "".to_string(), true).await;
    // });
    let last_trigger_time = Arc::new(Mutex::new(Instant::now()));
    let app_handle = app.clone();
    match app.plugin(
        tauri_plugin_global_shortcut::Builder::new()
            .with_handler(
                move |app: &tauri::AppHandle<R>,
                      shortcut: &tauri_plugin_global_shortcut::Shortcut,
                      event: tauri_plugin_global_shortcut::ShortcutEvent| {
                    println!("{}", shortcut.into_string());
                    println!("{:?}", event.state());
                    let mut last_time = last_trigger_time.lock().unwrap();
                    let now = Instant::now();

                    // 防抖间隔 300ms
                    if now.duration_since(*last_time) < Duration::from_millis(300) {
                        return; // 直接忽略
                    }
                    *last_time = now;
                    if event.state() == ShortcutState::Pressed {
                        if shortcut.into_string().eq("shift+control+KeyQ") {
                            let app_handle = app_handle.clone();
                            sleep(Duration::from_millis(200));
                            window_util::open_editor(app_handle, Some("".to_string()), "文本编辑-text", None);
                        } else if shortcut.into_string().eq("shift+control+KeyE") {
                            let lebel = "main".to_string();
                            if let Some(win) = app.get_webview_window(&lebel) {
                                println!("窗口已启动!");
                                let _ = win.show();
                                let _ = win.set_always_on_top(true);
                                let _ = win.set_focus();
                                sleep(Duration::from_millis(100));
                                let _ = win.set_always_on_top(false);
                            } else {
                                let app_handle = app.clone();
                                window_util::open_editor(app_handle, Some("".to_string()), "文本编辑-text", None);
                            }
                        }
                    }
                },
            )
            .build(),
    ) {
        Ok(_) => {
            app.global_shortcut()
                .register("shift+control+keyQ")
                .unwrap();
            app.global_shortcut()
                .register("shift+control+keyE")
                .unwrap();

            // #[cfg(target_os = "macos")]
            // if !is_accessibility() {
            //     // 打开系统“辅助功能”设置页
            //     std::process::Command::new("open")
            //         .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
            //         .spawn()
            //         .expect("failed to open system preferences");
            // }
            
        }
        Err(e) => {
            println!("失败： {}", e)
        }
    }
    Ok(())
}

// fn is_accessibility() -> bool {
//     unsafe {
//         unsafe extern "C" {
//             fn AXIsProcessTrusted() -> bool;
//         }
//         AXIsProcessTrusted()
//     }
// }